package com.heima.wemedia.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
       //TODO
        String name = dto.getName();
        String password = dto.getPassword();

        if(StrUtil.isBlank(password)||StrUtil.isBlank(name)){
            String token = AppJwtUtil.getToken(0L);
            return ResponseResult.okResult(token);
        }
        WmUser wmUser = this.lambdaQuery()
                .eq(WmUser::getName, name).one();
        if(wmUser==null){
            ResponseResult.errorResult(1002,"用户不存在");
        }
        String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw(password, gensalt);
        if(!hashpw.equals(wmUser.getPassword())){
            ResponseResult.errorResult(2,"用户密码错误");
        }

        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        Map<String,Object> map = new HashMap<>();
        long time = wmUser.getCreatedTime().getTime();
        wmUser.setPassword(null);
        map.put("user", wmUser);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}